package com.bjsxt.socketdemo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLOutput;

//接收客户端消息线程类
class ChatReceive extends Thread{

    Socket socket=null;

    public ChatReceive(Socket socket) {
        this.socket= socket;
    }

    @Override
    public void run() {
        this.receiveMsg();
    }

    private void receiveMsg(){
        BufferedReader br = null;
        try {
            br  =new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            while (true){
                String msg = br.readLine();
                synchronized ("abc"){
                    ChatRoomServer.buf="["+this.socket.getInetAddress()+"]"+msg;
                    //唤醒发送消息的线程对象
                    "abc".notifyAll();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }

    }
}
//向客户端发送消息的线程类
class ChatSend extends Thread{
    Socket socket=null;

    public ChatSend(Socket socket) {
        this.socket= socket;
    }

    @Override
    public void run() {
        this.sendMsg();
    }
    //将公共数据区的消息发送给客户端
    private void sendMsg(){
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(this.socket.getOutputStream());
            while(true){
                synchronized ("abc"){
                    "abc".wait();
                    pw.println(ChatRoomServer.buf);
                    pw.flush();
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(this.socket!=null){
                try {
                    this.socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (pw!=null){
                pw.close();
            }
        }

    }
}

public class ChatRoomServer {

    //定义公共数据区
    public static String buf;
    public static void main(String[] args) {
        System.out.println("Chat Server Version 1.0");
        System.out.println("Listen at 8888....");
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8888);
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println("连接到："+socket.getInetAddress());
                new ChatReceive(socket).start();
                new ChatSend(socket).start();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
